﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Contrib.Reviews.Models;
using Orchard;
using Orchard.Data;
using Contrib.Voting.Services;
using Contrib.Voting.Models;
using Orchard.Users.Services;
using Orchard.Security;
using So.ContribReviews.UserReviewedItems.ViewModels;
using Orchard.Users.Models;
using Orchard.ContentManagement;

namespace So.ContribReviews.UserReviewedItems.ViewModels
{
    public class UserReviewedItemsService : IUserReviewedItemsService
    {
        private readonly IOrchardServices _orchardServices;
        private readonly IVotingService _votingService;
        private readonly IRepository<ReviewRecord> _reviewRepository;
        private readonly IMembershipService _membershipService;

        public UserReviewedItemsService(IOrchardServices orchardServices, IRepository<ReviewRecord> reviewRepository, IVotingService votingService,
            IMembershipService membershipService)
        {
            _membershipService = membershipService;
            _votingService = votingService;
            _orchardServices = orchardServices;
            _reviewRepository = reviewRepository;
        }

        public UserReviewedItemsViewModel GetUserReviewedItems(int userId)
        {
            var currentUser = _orchardServices.ContentManager.Query<UserPart, UserPartRecord>().Where(u => u.Id == userId).List().FirstOrDefault();
            IEnumerable<VoteRecord> voteRecords = _votingService.Get(p => p.Username == currentUser.UserName);
            int[] voteIds = voteRecords.Select(s => s.Id).ToArray();
            IEnumerable<ReviewRecord> reviewRecords = _reviewRepository.Fetch(r => voteIds.Contains(r.VoteRecordId));

            var reviews = from v in voteRecords
                          join r in reviewRecords on v.Id equals r.VoteRecordId
                          select new UserReviewItemViewModel
                          {
                              ContentItem = _orchardServices.ContentManager.Get(v.ContentItemRecord.Id),
                              Review = new Review
                              {
                                  Id = r.Id,
                                  Comment = r.Comment,
                                  CreatedUtc = r.CreatedUtc,
                                  Rating = new Rating { CurrentVotingResult = _votingService.GetResult(r.ContentItemRecordId, "average") ?? new ResultRecord(), UserRating = v.Value },
                                  UserName = v.Username,
                                  IsCurrentUsersReview = currentUser.UserName != null ? v.Username == currentUser.UserName : false
                              }
                          };
            return new UserReviewedItemsViewModel()
            {
                UserReviewItemViewModels = reviews.ToList()
            };
        }
    }
}
